package com.fulihui.wgj.schedule.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.common.enums.WxSystemConfigKeyEnum;
import com.fulihui.weixinsdk.WeixinSDK;
import com.fulihui.weixinsdk.request.ComponentAccessTokenRequest;
import com.fulihui.weixinsdk.result.ComponentAccessTokenResult;
import com.fulihui.wgj.facade.request.system.WxSystemConfigRequest;
import com.fulihui.wgj.facade.result.system.WxSystemConfigResult;
import com.fulihui.wgj.facade.service.system.WxSystemCongfigService;
import com.fulihui.wgj.schedule.annotation.MutexLock;
import com.fulihui.wgj.schedule.config.AppParamsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author: JY 刷新开放平台Token
 * @date: 2018/6/19 16:48
 */
@Component
public class ComponentTokenJob {

    @Autowired
    WeixinSDK weixinSDK;

    @Autowired
    AppParamsConfig appParamsConfig;

    @Reference(version = "1.0.0")
    WxSystemCongfigService wxSystemCongfigService;

    private static final Logger logger  = LoggerFactory.getLogger(ComponentTokenJob.class);

    /**
     * Token更新时间 1时50分
     */
    private static final long TOKEN_REFRESH_PERIOD = (60+50) * 60 * 1000L;

    @MutexLock(node = "${job.node.componentTokenJob_entrance}")
    @Scheduled(cron = "${job.cron.componentTokenJob_entrance}")
    public void entrance(){

        //1.获取 数据库componentToken
        WxSystemConfigResult compnentTokenResult = wxSystemCongfigService.findConfigByCode(WxSystemConfigKeyEnum.component_access_token.getCode());
        //判断Token是否有效
        if(compnentTokenResult!=null && compnentTokenResult.getValue()!=null){
            if((compnentTokenResult.getValue().getGmtModified().getTime()+TOKEN_REFRESH_PERIOD)>System.currentTimeMillis()){
                logger.info("ComponentToken 有效 跳过刷新");
                return;
            }
        }

        //2.获取Ticket
        WxSystemConfigResult ticketResult = wxSystemCongfigService.findConfigByCode(WxSystemConfigKeyEnum.component_verify_ticket.getCode());
        //判断Ticket
        if(ticketResult.getValue()==null || ticketResult.getValue().isExire()){
            logger.error("Ticket 失效");
            return;
        }

        //3.刷新Token
        ComponentAccessTokenRequest tokenRequest = new ComponentAccessTokenRequest();
        tokenRequest.setComponent_appid(appParamsConfig.getAppId());
        tokenRequest.setComponent_appsecret(appParamsConfig.getAppSecret());
        tokenRequest.setComponent_verify_ticket(ticketResult.getValue().getDescript());
        ComponentAccessTokenResult componentAccessTokenResult = weixinSDK.invokeService(tokenRequest);
        if(componentAccessTokenResult == null || !componentAccessTokenResult.isSuccess()){
            logger.error("刷新ComponentAccessToken失败");
            return;
        }

        //4.写入数据库
        WxSystemConfigRequest configRequest = new WxSystemConfigRequest();
        configRequest.setCode(WxSystemConfigKeyEnum.component_access_token.getCode());
        configRequest.setDescript(componentAccessTokenResult.getComponent_access_token());
        wxSystemCongfigService.refreshConfig(configRequest);
    }
}
